/*
 使用工具类的编写
*/
#ifndef __M_UTIL_H__
#define __M_UTIL_H__
#include <iostream>
#include <ctime>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

namespace mylog{
  namespace Util{
    class Date{
        public:
          static size_t getTime(){
            return (size_t)time(nullptr);
          }
    };

    class File{
        public:
          static bool Exists(const std::string &pathname){
            struct stat st;
            //没有对应文件，返回-1;找到对应文件，返回0
            if(stat(pathname.c_str(), &st) < 0){
                return false; 
            }
            return true;
          }
          static std::string Path(const std::string &pathname){
            if(pathname.empty())  return ".";  //默认路径为当前路径
            auto pos = pathname.find_last_of("/\\");
            if(pos == std::string::npos)  return "."; //没找到分隔符，默认当前路径
            return pathname.substr(0, pos + 1); //切割子串
          }
          static void CreateDirectory(const std::string &pathname){
            if(pathname.empty())  return; //为空不用创建
            if(Exists(pathname))  return; //已经存在不用创建
            size_t pos, idx = 0;
            while(idx < pathname.size()){
               pos = pathname.find_first_of("/\\", idx);  //从idx开始找分隔符
               //假如没有找到分隔符,说明当前pathname就是对应的文件名
               if(pos == std::string::npos){
                   mkdir(pathname.c_str(), 0755);
                   return;
               }
               //"\"和"\\"直接跳过
               if(pos == idx){
                   idx = pos + 1;
                   continue;
               }
               std::string subdir = pathname.substr(0, pos);
               if(subdir == "." || subdir == ".."){
                 idx = pos + 1;
                 continue;
               }
               if(Exists(subdir)){
                 idx = pos + 1;
                 continue;
               }

               //创建对应的目录
               mkdir(subdir.c_str(), 0755);
               idx = pos + 1;
            }
          }
    };
  }
}

#endif
